package com.nikmesoft.android.ebox.activities;

import java.io.File;
import java.io.IOException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;

import android.provider.MediaStore;
import android.util.Log;

import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.nikmesoft.android.ebox.R;
import com.nikmesoft.android.ebox.adapters.ItemAdapter;
import com.nikmesoft.android.ebox.helpers.FileHelper;
import com.nikmesoft.android.ebox.models.Item;
import com.nikmesoft.android.ebox.models.Item.Type;

public class PhotosActivity extends Activity {
	private ArrayList<Item> items = new ArrayList<Item>();
	private static final int REQUEST_CODE_VIEW = 101;
	private static final int REQUEST_CODE_ADD_GALLERY = 100;
	private static final int REQUEST_CODE_TAKE_PHOTO = 102;
	public static final int MEDIA_TYPE_IMAGE = 1;
	private ListView myListView;
	private ItemAdapter itemAdapter;
	private ArrayList<String> paths;
	private ImageButton imbt_back;
	private ImageButton imbt_add_photos;
	private ImageButton imbt_home;
	private Item selected_image;
	private int home = 0;
	private int pos;
	private Uri fileUri;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_photo);
		imbt_back = (ImageButton) findViewById(R.id.imbt_back_photos);
		imbt_add_photos = (ImageButton) findViewById(R.id.btn_add_photos);
		imbt_home = (ImageButton) findViewById(R.id.imbt_home_photos);
		registerForContextMenu(imbt_add_photos);
		init();
	}

	private void init() {
		myListView = (ListView) findViewById(R.id.myListViewPhotos);
		imbt_add_photos.setBackgroundColor(Color.TRANSPARENT);
		imbt_home.setBackgroundColor(Color.TRANSPARENT);
		imbt_back.setBackgroundColor(Color.TRANSPARENT);
		imbt_back.setVisibility(View.INVISIBLE);
		registerForContextMenu(myListView);
		myListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				Item item = itemAdapter.getItem(position);
				if (item.getType() == Item.Type.Folder) {
					goToFolder(item.getName());
					imbt_back.setVisibility(View.VISIBLE);
					imbt_home.setVisibility(View.INVISIBLE);
					home++;
				} else if (item.getType() == Item.Type.Photo) {
					selected_image = itemAdapter.getItem(position);
					Intent intent = new Intent(PhotosActivity.this,
							ViewPhotosActivity.class);
					intent.putExtra("KEY", selected_image.getName());
					intent.putExtra("PATH", pathToString());
					intent.putExtra("Currentpath", getCurrentPath());
					startActivityForResult(intent, REQUEST_CODE_VIEW);

				}

			}

		});
		paths = new ArrayList<String>();
		items = new ArrayList<Item>();
		itemAdapter = new ItemAdapter(this, R.layout.list_item, items);
		myListView.setAdapter(itemAdapter);
		retrieveCurrentPath();
	}

	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		String ext = "";
		if (AdapterView.AdapterContextMenuInfo.class.isInstance(menuInfo)) {
			AdapterContextMenuInfo adapterMenuInfo = (AdapterContextMenuInfo) menuInfo;
			pos = adapterMenuInfo.position;
			ext = getItemname(pos).substring(
					(getItemname(pos).lastIndexOf(".") + 1),
					getItemname(pos).length());
		}

		if (v == imbt_add_photos) {
			menu.setHeaderTitle("Add");
			menu.add(0, v.getId(), 0,
					getString(R.string.activity_photos_menu_folder));
			menu.add(1, v.getId(), 0,
					getString(R.string.activity_photos_menu_gallery));
			menu.add(2, v.getId(), 0,
					getString(R.string.activity_photos_menu_camera));
		} else if (v == myListView) {
			menu.setHeaderTitle("Task");
			if (ext.equals(getItemname(pos))) {
				menu.add(3, v.getId(), 0,
						getString(R.string.contextmenu_item_rename));
				menu.add(4, v.getId(), 0,
						getString(R.string.contextmenu_item_delete));
			} else {

				menu.add(5, v.getId(), 0,
						getString(R.string.contextmenu_item_rename));
				menu.add(6, v.getId(), 0,
						getString(R.string.contextmenu_item_share));
				menu.add(7, v.getId(), 0,
						getString(R.string.contextmenu_item_back2galley));
				menu.add(8, v.getId(), 0,
						getString(R.string.contextmenu_item_delete));

			}
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		if (item.getTitle().equals(
				getString(R.string.activity_photos_menu_folder))) {
			createFolderDialog(item.getItemId());
		} else if (item.getTitle().equals(
				getString(R.string.activity_photos_menu_gallery))) {
			chooseFromGallery(item.getItemId());
		} else if (item.getTitle().equals(
				getString(R.string.activity_photos_menu_camera))) {
			takeFromCamera(item.getItemId());
		} else if (item.getTitle().equals(
				getString(R.string.contextmenu_item_rename))) {
			createRenameDialog(item.getItemId());

		} else if (item.getTitle().equals(
				getString(R.string.contextmenu_item_share))) {
			share(pos);
		} else if (item.getTitle().equals(
				getString(R.string.contextmenu_item_back2galley))) {
			saveTogallery();
			Toast.makeText(PhotosActivity.this, "Image's saved back...!",
					Toast.LENGTH_SHORT).show();
		} else if (item.getTitle().equals(
				getString(R.string.contextmenu_item_delete))) {
			confirmDialog(item.getItemId());
		} else {
			return false;
		}
		return true;
	}

	public void share(int pos) {
		selected_image = itemAdapter.getItem(pos);
		String file_path = getCurrentPath() + selected_image.getName();
		Intent shareIntent = new Intent(Intent.ACTION_SEND);
		Uri phototUri = Uri.parse(file_path);
		shareIntent.setData(phototUri);
		shareIntent.setType("image/*");
		shareIntent.putExtra(Intent.EXTRA_STREAM, phototUri);
		startActivity(Intent.createChooser(shareIntent, "Share Via"));

	}

	public void saveTogallery() {
		selected_image = itemAdapter.getItem(pos);
		String file_path = getCurrentPath() + selected_image.getName();
		File sourceFile = new File(file_path);
		File desFile = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/DCIM/" + getItemname(pos));
		if (!desFile.exists()) {
			try {
				desFile.createNewFile();
				copyDirectory(sourceFile, desFile);
				sourceFile.delete();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		retrieveCurrentPath();

	}

	public void delete(int pos) {
		selected_image = itemAdapter.getItem(pos);
		String file_path = getCurrentPath() + selected_image.getName();
		File f = new File(file_path);
		DeleteRecursive(f);
		retrieveCurrentPath();
	}

	public void saveRecursive(String file_path) {

	}

	void DeleteRecursive(File fileOrDirectory) {
		if (fileOrDirectory.isDirectory())
			for (File child : fileOrDirectory.listFiles())
				DeleteRecursive(child);

		fileOrDirectory.delete();
	}

	public String getItemname(int pos) {
		selected_image = itemAdapter.getItem(pos);
		String filename = selected_image.getName();
		return filename;

	}

	public void confirmDialog(int id) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Delete");
		alert.setMessage("Are you sure ?");

		// Set an EditText view to get user input

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				delete(pos);

			}
		});
		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// Canceled.
					}
				});

		alert.show();

	}

	public void createRenameDialog(int id) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Rename");
		alert.setMessage("Enter new name");
		String test = getItemname(pos);
		String ext;
		ext = "."
				+ getItemname(pos).substring(
						(getItemname(pos).lastIndexOf(".") + 1),
						getItemname(pos).length());

		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		if (ext.equals("." + getItemname(pos))) {
			ext = "";

		}
		input.setHint(test.substring(0, test.length() - ext.length()));
		alert.setView(input);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String ext;
				String newname = input.getText().toString().trim();

				if (newname.equals("")) {
					Toast.makeText(PhotosActivity.this, "Name is empty!",
							Toast.LENGTH_SHORT).show();
				} else {
					File dir = new File(getCurrentPath());
					ext = "."
							+ getItemname(pos).substring(
									(getItemname(pos).lastIndexOf(".") + 1),
									getItemname(pos).length());
					if (ext.equals("." + getItemname(pos))) {
						ext = "";
					}

					if (dir.exists()) {
						File from = new File(dir, getItemname(pos));
						File to = new File(dir, newname + ext);
						if (to.exists()) {
							Toast.makeText(PhotosActivity.this,
									"Name is exist!", Toast.LENGTH_SHORT)
									.show();
						} else {
							from.renameTo(to);
							Toast.makeText(PhotosActivity.this,
									"Rename complete..!", Toast.LENGTH_SHORT)
									.show();
						}
					}

					retrieveCurrentPath();

				}
			}
		});
		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// Canceled.
					}
				});

		alert.show();

	}

	public void createFolderDialog(int id) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("New Folder");
		alert.setMessage("Enter folder's name");

		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		input.setHint("Some text ...");
		alert.setView(input);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String foldername = input.getText().toString().trim();
				if (foldername.equals("")) {
					Toast.makeText(PhotosActivity.this, "Name is empty",
							Toast.LENGTH_SHORT).show();
				} else {

					FileHelper.getInstance().addFolder(
							pathToString() + foldername + "/", Type.Photo);
					retrieveCurrentPath();
				}
			}
		});

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// Canceled.
					}
				});

		alert.show();

	}

	private void chooseFromGallery(int id) {
		Intent i = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(i, REQUEST_CODE_ADD_GALLERY);

	}

	private void takeFromCamera(int id) {

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		fileUri = Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), "tmp_ebox.jpg"));

		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileUri);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);

	}

	public String getCurrentPath() {
		String currentpath = FileHelper.getInstance().getFullPath("",
				Type.Photo)
				+ pathToString();
		return currentpath;
	}

	@SuppressLint("SimpleDateFormat")
	public File getOutputMediaFile() {
		File mediaStorageDir = new File(getCurrentPath());
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d("MyCameraApp", "failed to create directory");
				return null;
			}
		}
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		return new File(mediaStorageDir.getPath() + File.separator + "IMG_"
				+ timeStamp + ".jpg");
	}

	public void onClickAddPhotos(View v) {
		openContextMenu(v);
	}

	public static void copyDirectory(File sourceLocation, File targetLocation)
			throws IOException {

		/*
		 * if (sourceLocation.isDirectory()) { if (!targetLocation.exists() &&
		 * !targetLocation.mkdirs()) { throw new
		 * IOException("Cannot create dir " + targetLocation.getAbsolutePath());
		 * }
		 * 
		 * String[] children = sourceLocation.list(); for (int i = 0; i <
		 * children.length; i++) { copyDirectory(new File(sourceLocation,
		 * children[i]), new File( targetLocation, children[i])); } } else {
		 * 
		 * // make sure the directory we plan to store the recording in exists
		 * 
		 * File directory = targetLocation.getParentFile(); if (directory !=
		 * null && !directory.exists() && !directory.mkdirs()) { throw new
		 * IOException("Cannot create dir " + directory.getAbsolutePath()); }
		 * 
		 * FileHelper.getInstance().encode(sourceLocation, targetLocation); }
		 */

		FileHelper.getInstance().encode(sourceLocation, targetLocation);
	}

	public static String getFileNameByUri(Uri uri, Cursor cursor) {
		String fileName = "unknown";// default fileName
		Uri filePathUri = uri;
		if (uri.getScheme().toString().compareTo("content") == 0) {
			if (cursor.moveToFirst()) {
				int column_index = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);// Instead
				filePathUri = Uri.parse(cursor.getString(column_index));
				fileName = filePathUri.getLastPathSegment().toString();
			}
		} else if (uri.getScheme().compareTo("file") == 0) {
			fileName = filePathUri.getLastPathSegment().toString();
		} else {
			fileName = fileName + "_"
					+ filePathUri.getLastPathSegment().toString();
		}
		return fileName;
	}

	public String getRealPath(Uri uri) {
		String[] filePathColumn = { MediaStore.Images.Media.DATA };
		Cursor cursor = getContentResolver().query(uri, filePathColumn, null,
				null, null);
		cursor.moveToFirst();
		int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
		String sourceImagePath = cursor.getString(columnIndex);
		cursor.close();
		return sourceImagePath;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE_TAKE_PHOTO) {
			if (resultCode == RESULT_OK) {

				File sourceFile = new File(
						Environment.getExternalStorageDirectory(),
						"tmp_ebox.jpg");
				try {
					File desFile = getOutputMediaFile();
					copyDirectory(sourceFile, desFile);
					sourceFile.delete();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				retrieveCurrentPath();
			} else if (resultCode == RESULT_CANCELED) {
				// User cancelled the image capture
			} else {
				// Image capture failed, advise user
			}
		} else if (requestCode == REQUEST_CODE_ADD_GALLERY) {
			if (resultCode == RESULT_OK) {

				Uri selectedImage = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				Cursor cursor = getContentResolver().query(selectedImage,
						filePathColumn, null, null, null);
				String sourceImagePath = getRealPath(selectedImage);
				String sourceFileName = getFileNameByUri(selectedImage, cursor);
				String destinationImagePath = getCurrentPath() + sourceFileName;
				Toast.makeText(getApplicationContext(), "Image added... ",
						Toast.LENGTH_SHORT).show();
				File source_file = new File(sourceImagePath);
				File des_file = new File(destinationImagePath);
				if (!des_file.exists()) {
					try {
						des_file.createNewFile();
						copyDirectory(source_file, des_file);
						// source_file.delete();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}
			retrieveCurrentPath();
		} else if (requestCode == REQUEST_CODE_VIEW) {
			if (resultCode == RESULT_OK)
				
			retrieveCurrentPath();

		}

	}

	public void Back(View v) {
		home--;
		if (home == 0) {
			imbt_back.setVisibility(View.INVISIBLE);
			imbt_home.setVisibility(View.VISIBLE);
		}
		backToParentFolder();
	}

	@Override
	public void onBackPressed() {
		if (paths.size() > 0) {
			home--;
			if (home == 0) {
				imbt_back.setVisibility(View.INVISIBLE);
				imbt_home.setVisibility(View.VISIBLE);
			}
			backToParentFolder();

		} else {
			super.onBackPressed();
		}

	}

	// File processing
	public String pathToString() {
		String s = "";
		for (String name : paths) {
			s += name + "/";
		}
		return s;
	}

	private void retrieveCurrentPath() {
		items.clear();
		items = FileHelper.getInstance()
				.getAllItems(pathToString(), Type.Photo);
		itemAdapter.clear();
		for (Item item : items) {
			itemAdapter.add(item);
		}
		itemAdapter.notifyDataSetChanged();
	}

	private void backToParentFolder() {
		if (paths.size() > 0) {
			paths.remove(paths.size() - 1);
			retrieveCurrentPath();
		}
	}

	private void goToFolder(String folderName) {
		paths.add(folderName);
		retrieveCurrentPath();
	}
}
